import { ref, onMounted } from 'vue'
import { destinationApi } from '@/api/public/destination'
import type { Destination } from '@/types/destination'
import type { Router } from 'vue-router'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

export const useDestination = () => {
  const destinations = ref<Destination[]>([])
  const searchKeyword = ref('')
  const isSearchResult = ref(false)
  const router = useRouter()
  const fetchDestinations = async () => {
    try {
      const response = await destinationApi.getList()
      if (response.data.code === 200) {
        destinations.value = response.data.data.content
      }
    } catch (error) {
      console.error('获取景点列表失败:', error)
      ElMessage.error('获取景点列表失败')
    }
  }

  const handleSearch = async () => {
    if (!searchKeyword.value.trim()) {
      ElMessage.warning('请输入搜索关键词')
      return
    }

    try {
      const response = await destinationApi.search(searchKeyword.value)
      if (response.data.code === 200) {
        destinations.value = response.data.data.content
        isSearchResult.value = true
      }
    } catch (error) {
      console.error('搜索失败:', error)
      ElMessage.error('搜索失败')
    }
  }

  const clearSearch = () => {
    searchKeyword.value = ''
    isSearchResult.value = false
    fetchDestinations()
  }

  const goToDetail = (id: number) => {
    router.push(`/destination/${id}`)
  }

  onMounted(() => {
    fetchDestinations()
  })

  return {
    destinations,
    searchKeyword,
    isSearchResult,
    handleSearch,
    clearSearch,
    goToDetail
  }
} 
